import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
import joblib
import pandas as pd

data = pd.read_csv('The Martian_reviews_cleaned.csv')

# 中文分词
data['review_seg'] = data['Review'].apply(lambda x: ' '.join(jieba.cut(x)))

# 构建TF-IDF特征
tfidf = TfidfVectorizer()
X = tfidf.fit_transform(data['review_seg'])
y = data['Sentiment']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)
# 创建SVM模型并训练
clf = SVC(kernel='rbf')
clf.fit(X_train, y_train)

# 保存模型
joblib.dump(clf, 'sentiment_classifier_svm.pkl')
# 保存 TfidfVectorizer 对象
joblib.dump(tfidf, 'tfidf_vectorizer_svm.pkl')

# 加载 TfidfVectorizer 对象
tfidf = joblib.load('tfidf_vectorizer_svm.pkl')

accuracy = clf.score(X_test, y_test)
print(f'SVM模型在测试集上的准确率为: {accuracy}')
# 加载保存的模型
clf = joblib.load('sentiment_classifier_svm.pkl')

# 使用模型进行预测
new_text = input('请输入评论：')
new_text_seg = ' '.join(jieba.cut(new_text))
new_text_feature = tfidf.transform([new_text_seg])
predicted_label = clf.predict(new_text_feature)[0]
print(f'新文本的情感预测结果为: {predicted_label}')